<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <!-- 机构树 -->
          <div v-for="item in btnList.beforeList" :key="item.value">
            <el-button
              v-if="item.value === 'add'"
              :plain="true"
              :disabled="addBtn"
              @click="addOrg"
              >新增</el-button
            >
            <el-button
              v-if="item.value === 'delDept'"
              :plain="true"
              :disabled="!canDelete"
              @click="delDept"
              >删除</el-button
            >
            <el-button
              v-if="item.value === 'orgDeptImport'"
              :plain="true"
              @click="downloadTemplate('org_dept_import')"
              >下载部门模板</el-button
            >
            <el-upload
              v-if="item.value === 'orgDeptInput'"
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入部门</el-button>
            </el-upload>
            <el-button
              v-if="item.value === 'orgUserImport'"
              :plain="true"
              @click="downloadTemplate('org_user_import')"
              >下载人员模板</el-button
            >
            <el-upload
              v-if="item.value === 'orgUserInput'"
              :headers="uploadUserInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :action="uploadUserInfo.action"
            >
              <el-button>导入人员</el-button>
            </el-upload>
            <el-button
              v-if="item.value === 'exportExcel'"
              :plain="true"
              @click="exportExcel"
              >导出Excel</el-button
            >
          </div>
          <el-dropdown v-if="btnList.afterList.length">
            <el-button>
              更多<i
                class="el-icon-arrow-down el-icon--right"
                style="fontsize: 12px"
              ></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in btnList.afterList"
                  :key="item.value"
                >
                  <div
                    v-if="item.value === 'add'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    :disabled="addBtn"
                    @click="addOrg"
                  >
                    新增
                  </div>
                  <div
                    v-if="item.value === 'delDept'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    :disabled="!canDelete"
                    @click="delDept"
                  >
                    删除
                  </div>
                  <div
                    v-if="item.value === 'orgDeptImport'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    @click="downloadTemplate('org_dept_import')"
                  >
                    下载部门模板
                  </div>
                  <el-upload
                    v-if="item.value === 'orgDeptInput'"
                    :headers="uploadInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :action="uploadInfo.action"
                  >
                    <div style="width: 100%; height: 100%; padding: 0 10px">
                      导入部门
                    </div>
                  </el-upload>
                  <div
                    v-if="item.value === 'orgUserImport'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    @click="downloadTemplate('org_user_import')"
                  >
                    下载人员模板
                  </div>
                  <el-upload
                    v-if="item.value === 'orgUserInput'"
                    :headers="uploadUserInfo.headers"
                    :show-file-list="false"
                    :on-error="uploadError"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :action="uploadUserInfo.action"
                  >
                    <div style="width: 100%; height: 100%; padding: 0 10px">
                      {{ item.label }}
                    </div>
                  </el-upload>
                  <div
                    v-if="item.value === 'exportExcel'"
                    style="width: 100%; height: 100%; padding: 0 10px"
                    :plain="true"
                    @click="exportExcel"
                  >导出Excel
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="left-container-header border-style-bottom">
          <el-input
            v-model="treeInfo.query.keyword"
            style="flex: 1; margin-right: 10px"
            :clearable="true"
            placeholder="请输入部门名称/编码"
            @keyup.enter.native="init"
          ></el-input>
          <el-button @click="init">搜索</el-button>
        </div>
        <div class="left-container-main main-flex">
          <el-tree
            ref="menuTree"
            :data="treeInfo.data"
            highlight-current
            :props="treeInfo.defaultProps"
            node-key="id"
            :default-checked-keys="[treeInfo.checked]"
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right-container">
        <div v-if="showDeptSubmitBox" class="layui-card-body">
          <!-- 部门 -->
          <div class="layui-btn-container border-style-bottom">
            <el-button :plain="true" :disabled="saveBtn" @click="updateOrg">{{
              $t('btn_save')
            }}</el-button>
          </div>
          <div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formOrgInfo.ref"
              :data="formOrgInfo.data"
              :field-list="formOrgInfo.fieldList"
              :rules="formOrgInfo.rules"
              :label-width="formOrgInfo.labelWidth"
            >
              <template v-slot:form-coreResource>
                <span v-if="UserBox" class="slip-edit" @click="addDeptResource"
                  >选择</span
                >
                <span v-else>选择</span>
              </template>
              <template v-slot:form-isAllDept>
                <el-checkbox v-model="formOrgInfo.data.isAllDept"></el-checkbox>
              </template>
              <template v-slot:form-isAllDepot>
                <el-checkbox
                  v-model="formOrgInfo.data.isAllDepot"
                ></el-checkbox>
              </template>
              <template v-slot:form-isAllSupplier>
                <el-checkbox
                  v-model="formOrgInfo.data.isAllSupplier"
                ></el-checkbox>
              </template>
              <template v-slot:form-managerUserName>
                <el-input
                  v-model="formOrgInfo.data.managerUserName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择部门负责人"
                >
                  <template #append>
                    <el-icon @click="selectDeptUser"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptClassificationValue>
                <el-input
                  v-model="formOrgInfo.data.deptClassificationValue"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择部门分类"
                >
                  <template #append>
                    <el-icon @click="selectDeptClassfication"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <!-- 用户 -->
        <div v-if="UserBox" class="layui-card-body">
          <div class="opt-header border-style-bottom">
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template
                v-if="$permission('organization:userAdd')"
                v-slot:filter-addUser
              >
                <el-button :disabled="currentDeptId <= 0" @click="addUser"
                  >新增</el-button
                >
              </template>
              <template
                v-if="$permission('organization:userDel')"
                v-slot:filter-btnDelete
              >
                <el-button
                  :disabled="!tableInfo.selections.length"
                  @click="del()"
                  >删除</el-button
                >
              </template>
            </page-filter>
          </div>
          <table-container
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            v-model:data="tableInfo.data"
            :api="tableInfo.api"
            :query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            @handleEvent="handleEvent"
          >
            <template v-slot:col-userName="scope">
              <span class="slip-edit" @click="openUserInfoDetails(scope.row)">{{
                scope.row.userName
              }}</span>
            </template>
            <template v-slot:col-electronicSignaturePaths="scope">
              <div
                v-if="
                  scope.row.electronicSignaturePaths &&
                  scope.row.electronicSignaturePaths.length &&
                  scope.row.electronicSignaturePaths[0].filePath
                "
                class="showImage"
                @click="viewImg(scope.row, scope.$index)"
              >
                <el-image
                  class="image"
                  :src="
                    baseUrl +
                    '/pub' +
                    scope.row.electronicSignaturePaths[0].filePath
                  "
                ></el-image>
              </div>
              <tableUploadImg
                v-else
                title="上传签名"
                :index="scope.$index"
                @upDateUpload="upDateUpload"
              />
            </template>
          </table-container>
        </div>
      </div>
      <!-- 新增修改弹窗 -->
      <page-dialog
        v-if="userDialogInfo.visible"
        :title="userDialogInfo.title[userDialogInfo.type]"
        v-model:visible="userDialogInfo.visible"
        :width="userDialogInfo.width"
        :bt-loading="userDialogInfo.btLoading"
        :bt-list="userDialogInfo.btList"
      >
        <!-- form -->
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="userFormInfo.ref"
          :data="userFormInfo.data"
          :field-list="userFormInfo.fieldList"
          :rules="userFormInfo.rules"
          :label-width="userFormInfo.labelWidth"
        >
          <template v-slot:form-isAllDept>
            <el-checkbox v-model="userFormInfo.data.isAllDept"></el-checkbox>
          </template>
          <template v-slot:form-isAllDepot>
            <el-checkbox v-model="userFormInfo.data.isAllDepot"></el-checkbox>
          </template>
          <template v-slot:form-isAllSupplier>
            <el-checkbox
              v-model="userFormInfo.data.isAllSupplier"
            ></el-checkbox>
          </template>
        </page-form>
      </page-dialog>
      <page-dialog
        v-if="userInfoDetails.visible"
        :title="userInfoDetails.title"
        v-model:visible="userInfoDetails.visible"
        :width="userInfoDetails.width"
        :bt-list="userInfoDetails.btList"
      >
        <basic-information :info="infoList"></basic-information>
      </page-dialog>
      <!---新增部门--->
      <page-dialog
        v-if="modifyInfo.visible"
        :title="modifyInfo.title"
        v-model:visible="modifyInfo.visible"
        :width="modifyInfo.width"
        :bt-list="modifyInfo.btList"
      >
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="formOrgInfo.ref"
          :data="formOrgInfo.modifyData"
          :field-list="formOrgInfo.modifyFieldList"
          :rules="formOrgInfo.rules"
          :label-width="formOrgInfo.labelWidth"
        >
          <template v-slot:form-isAllDept>
            <el-checkbox
              v-model="formOrgInfo.modifyData.isAllDept"
            ></el-checkbox>
          </template>
          <template v-slot:form-isAllDepot>
            <el-checkbox
              v-model="formOrgInfo.modifyData.isAllDepot"
            ></el-checkbox>
          </template>
          <template v-slot:form-isAllSupplier>
            <el-checkbox
              v-model="formOrgInfo.modifyData.isAllSupplier"
            ></el-checkbox>
          </template>
          <template v-slot:form-deptClassificationValue>
            <el-input
              v-model="formOrgInfo.modifyData.deptClassificationValue"
              class="not-mongolia"
              type="input"
              :required="true"
              :disabled="true"
              placeholder="请选择部门分类"
            >
              <template #append>
                <el-icon @click="selectDeptClassfication"
                  ><MoreFilled
                /></el-icon>
              </template>
            </el-input>
          </template>
          <template v-slot:form-isCreateDepotTemp>
            <el-checkbox
              :disabled="formOrgInfo.modifyData.status === 0"
              v-model="formOrgInfo.modifyData.isCreateDepotTemp"
            ></el-checkbox>
          </template>
        </page-form>
      </page-dialog>
      <SelectDepot
        v-if="showDepot"
        v-model:show-dialog="showDepot"
        :default-list="defaultDepotList"
        @callback="depotCallback"
      />
      <select-role
        v-if="selectRoleInfo.visible"
        v-model:show-dialog="selectRoleInfo.visible"
        :default-list="selectRoleInfo.defaultList"
        @callback="addRoleCallback"
      />
      <select-auth
        v-if="selectAuthInfo.visible"
        v-model:show-dialog="selectAuthInfo.visible"
        :query="selectAuthInfo.query"
        :query-tree="selectAuthInfo.queryTree"
        @callback="addAuthCallback"
      />
      <select-resource
        v-if="selectResourceInfo.visible"
        :query="userResourceQuery"
        :from-type="selectResourceInfo.fromType"
        v-model:show-dialog="selectResourceInfo.visible"
        :select-resource-info="selectResourceInfo"
        :default-list="selectResourceInfo.defaultList"
        :user-resource-disabled-list="userResourceDisabledList"
        @callback="addResourceCallback"
      />
      <SelectDept
        v-if="deptInfo.visible"
        v-model:show-dialog="deptInfo.visible"
        :query="deptInfo.query"
        :check-box="false"
        :highlight-row="true"
        @callback="selectDeptCallback"
      />
      <SelectUsers
        v-if="selectUserInfo.visible"
        v-model:show-dialog="selectUserInfo.visible"
        :query="selectUserInfo.query"
        :api="selectUserInfo.api"
        :check-box="false"
        :highlight-row="true"
        :save-empty="true"
        @callback="selectUserInfoBack"
      />
      <SelectUsers
        v-if="selectManageClassfication.visible"
        v-model:show-dialog="selectManageClassfication.visible"
        :query="selectManageClassfication.query"
        :title="selectManageClassfication.title"
        :fieldList="selectManageClassfication.fieldList"
        :filterInfoList="selectManageClassfication.filterInfoList"
        :api="selectManageClassfication.api"
        :check-box="false"
        :highlight-row="true"
        :save-empty="true"
        @callback="selectManageClassficationBack"
      />
    </div>
    <EleGallery
      v-if="viewImgInfo.visible"
      v-model:show-dialog="viewImgInfo.visible"
      :file-list="viewImgInfo.list"
      :title="viewImgInfo.title"
      :show-delete="true"
      :multiple-sheets="true"
      @callbackEle="callbackEle"
    />
  </div>
</template>

<script setup name="organization">
import { resetPassword } from '@/api/pub.js'
import EleGallery from '@/components/NewUpload/eleGallery'
import { mappingUserRole, deleteMappingUserRole } from '@/api/mapping'
import { getDeptClassificationPage } from '@/api/core'
import {
  getDeptTrees,
  createDeptWithPrimaryKey,
  updateDept,
  getDeptDetail,
  batchUpdateCoreResources,
  deleteCoreResourcesByEntity,
  resourcesUpdateList,
  getCoreResourcesAll,
  deleteDept,
  exportDets
} from '@/api/core'
import {
  getOrganizationUserPage,
  createUser,
  updateUser,
  adjustDept,
  deleteUser,
  batchUpdatePermissions,
  deletePermissionsByEntity,
  updateElectronicSignaturePath,
} from '@/api/base'
import tableUploadImg from '@/components/NewUpload/tableUploadImg'
import { ElLoading } from 'element-plus'
import SelectUsers from '@/components/SelectUsers/index'
import _ from 'lodash'
import { exportTemplateExcel } from '@/api/pub'

const { proxy } = getCurrentInstance()
const $route = useRoute()

const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const btnList = ref({
  beforeList: [],
  afterList: [],
})
const hideNum = ref(2)
const uploadInfo = ref({
  action: baseUrl.value + '/core/depts/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const uploadUserInfo = ref({
  action: baseUrl.value + '/base/users/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const addBtn = ref(true) //控制左侧树节点上方新增按钮状态
const saveBtn = ref(true)
// 权限树
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
  selectNode: {},
  query: {
    keyword: '',
  },
})
const formOrgInfo = ref({
  ref: null,
  data: {},
  modifyData: {},
  labelWidth: '120px',
  fieldList: [
    {
      label: proxy.$t('dept_name'),
      value: 'name',
      type: 'input',
    },
    {
      label: proxy.$t('dept_code'),
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    { label: '部门分类', value: 'deptClassificationValue', type: 'slot' },
    { label: '资源', value: 'coreResource', type: 'slot' },
    { label: '所有新增部门', value: 'isAllDept', type: 'slot' },
    { label: '所有新增仓库', value: 'isAllDepot', type: 'slot' },
    { label: '所有新增供应商', value: 'isAllSupplier', type: 'slot' },
    { label: '部门负责人', value: 'managerUserName', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  modifyFieldList: [
    {
      label: proxy.$t('dept_name'),
      value: 'name',
      type: 'input',
    },
    {
      label: proxy.$t('dept_code'),
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    { label: '部门分类', value: 'deptClassificationValue', type: 'slot' },
    { label: '所有新增部门', value: 'isAllDept', type: 'slot' },
    { label: '所有新增仓库', value: 'isAllDepot', type: 'slot' },
    { label: '所有新增供应商', value: 'isAllSupplier', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '是否新增仓库',
      value: 'isCreateDepotTemp',
      type: 'slot',
      className: 'full',
    },
    { label: '仓库名称', value: 'depotName', type: 'input', required: true },
    { label: '仓库编码', value: 'depotCode', type: 'input', required: true },
    {
      label: '仓库类型',
      value: 'depotType',
      type: 'select-model',
      required: true,
      code: 'depot_type',
    },
    {
      label: '用途类型',
      value: 'depotUseTypeId',
      multiple: true,
      type: 'select-model',
      required: true,
      code: 'depot_use_type',
      checkDefault: false,
    },
    {
      label: '是否以领定消',
      required: false,
      value: 'isReceiveConsume',
      type: 'select-model',
      code: 'yes_or_no',
      clearable: true,
    },
  ],
  rules: {
    code: [
      { required: true, message: '请输入部门编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    depotName: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
    depotCode: [{ required: true, message: '请输入仓库编码', trigger: 'blur' }],
    depotType: [
      { required: true, message: '请选择仓库类型', trigger: 'change' },
    ],
    depotUseTypeId: [
      { required: true, message: '请选择用途类型', trigger: 'change' },
    ],
    isReceiveConsume: [
      { required: false, message: '请选择是否以领定消', trigger: 'change' },
    ],
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    searchType: 'user',
    deptId: '',
    statusMult: '0,1',
    type: 'normal',
    orgId: proxy.$store.state.user.userInfo.user.orgId,
  },
  list: [
    { type: 'slot', value: 'addUser', label: '新增' },
    { type: 'slot', value: 'btnDelete', label: '删除' },
    {
      type: 'input',
      label: '工号/姓名',
      clearable: true,
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
const canNotAddUser = ref(true)
// 用户弹窗相关
const userDialogInfo = ref({
  title: {
    create: '添加用户',
    update: '修改用户',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeUserDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveUser,
      saveLoading: false,
      show: true,
    },
  ],
})
const userInfoDetails = ref({
  title: '员工信息',
  visible: false,
  width: '40%',
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeUserInfoDetails,
      show: true,
    },
  ],
})
// 用户表单相关
const userFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '工号',
      value: 'userName',
      type: 'input',
      required: true,
      disabled: true,
    },
    { label: '姓名', value: 'name', type: 'input', required: true },
    {
      label: '性别',
      value: 'sex',
      type: 'select-model',
      required: true,
      code: 'sex',
    },
    {
      label: '证件类型',
      value: 'certificateType',
      type: 'select-model',
      code: 'certificate_type',
    },
    {
      label: '证件号码',
      value: 'certificateNum',
      type: 'input',
      validator: proxy.$validate.idCard,
    },
    {
      label: '联系电话',
      value: 'tel',
      type: 'input',
      validator: proxy.$validate.cellphone,
    },
    {
      label: '邮箱',
      value: 'email',
      type: 'input',
      validator: proxy.$validate.mail,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    { label: '所有部门', value: 'isAllDept', type: 'slot' },
    { label: '所有仓库', value: 'isAllDepot', type: 'slot' },
    { label: '所有供应商', value: 'isAllSupplier', type: 'slot' },
    {
      label: '是否继承部门资源',
      value: 'isInheritance',
      type: 'select-model',
      code: 'yes_or_no',
    },
  ],
  rules: {},
  labelWidth: '150px',
})
const currentDeptId = ref(0)
const addOrUpdate = ref('')
const UserBox = ref(true)
const showDeptSubmitBox = ref(false)
const selectRows = ref([])
const tableData = ref([]) //编辑的用户数据
const isCascade = ref(undefined)
// const showFormItem = ref(false)
// 表格相关
const tableInfo = ref({
  selections: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getOrganizationUserPage,
  fieldList: [
    { label: '工号', value: 'userName', type: 'slot' },
    { label: '姓名', value: 'name' },
    { label: '部门', value: 'deptName' },
    { label: '性别', value: 'sexValue' },
    { label: '联系电话', value: 'tel' },
    { label: '角色', value: 'roleNames' },
    { label: '状态', value: 'statusValue' },
    // { label: '是否锁定', value: 'lockedValue' },
    { label: '签名', value: 'electronicSignaturePaths', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      { label: '角色', event: addRoles, show: true },
      { label: '权限', event: addAuth, show: true },
      { label: '资源', event: addUserResource, show: true },
      { label: '修改', event: editUser, show: true },
      { label: '调整部门', event: changeDept, show: true },
      { label: '启用/停用', event: enableOrdis, show: true },
      { label: '删除', event: del, show: true },
      { label: '重置密码', event: resetUserPassword, show: true },
      { label: '解锁', event: unlock, show: true },
    ],
  },
})
const showDepot = ref(false)
const defaultDepotList = ref([])
const selectRoleInfo = ref({
  visible: false,
  userId: '',
  defaultList: [],
})
const selectAuthInfo = ref({
  visible: false,
  userId: '',
  query: {
    subjectId: '',
    subjectType: 'user',
  },
  queryTree: {},
})
const selectResourceInfo = ref({
  visible: false,
  subjectId: '',
  fromType: '',
  defaultList: {},
})
const infoList = ref({
  data: {},
  fieldList: [
    { label: '工号', value: 'userName' },
    { label: '姓名', value: 'name' },
    { label: '性别', value: 'sexValue' },
    { label: '证件类型', value: 'certificateTypeValue' },
    { label: '证件号码', value: 'certificateNum' },
    { label: '联系电话', value: 'tel' },
    { label: '邮箱', value: 'email' },
    { label: '状态', value: 'statusValue' },
  ],
})
const deptInfo = ref({
  visible: false,
  userId: '',
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const addOrUpdateType = ref('')
const userResourceQuery = ref({})
const userResourceDisabledList = ref([])
const resourceKeys = ref([])
const orgRoute = ref({})
const modifyInfo = ref({
  visible: false,
  title: '新增部门',
  width: '60%',
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeModifyDept,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: updateOrg,
      saveLoading: false,
      show: true,
    },
  ],
})
const resourceCallbackData = ref({
  user: [],
  dept: [],
})
const uploadImageInfo = ref({
  myHeaders: {
    Authorization: proxy.$store.state.user.token,
  },
  action: baseUrl.value + '/pub/uploadfile',
  row: {},
})
const selectUserInfo = ref({
  visible: false,
  query: {},
  api: getOrganizationUserPage,
})
const selectManageClassfication = ref({
  visible: false,
  title: '选择部门分类',
  query: {},
  api: getDeptClassificationPage,
  filterInfoList: [
    {
      type: 'input',
      label: '名称',
      value: 'nameLike',
      event: search,
    },
    {
      type: 'input',
      label: '编码',
      value: 'codeLike',
      event: search,
    },
  ],
  fieldList: [
    {
      label: '名称',
      value: 'name',
    },
    {
      label: '编码',
      value: 'code',
    },
    {
      label: '上级分类',
      value: 'parentName',
    },
    {
      label: '备注',
      value: 'remark',
    },
  ],
})
const viewImgInfo = ref({
  visible: false,
  list: [],
  title: '签名',
  row: {},
  index: '',
})
const showDialog = ref(undefined)

const canDelete = computed(() => {
  return (
    treeInfo.value.selectNode.children &&
    treeInfo.value.selectNode.children.length === 0
  )
})
watch(
  () => formOrgInfo.value.modifyData.isCreateDepotTemp,
  (val) => {
    if (val) {
      formOrgInfo.value.rules = {
        ...formOrgInfo.value.rules,
        ...{
          depotName: [
            { required: true, message: '请输入仓库名称', trigger: 'blur' },
          ],
          depotCode: [
            { required: true, message: '请输入仓库编码', trigger: 'blur' },
          ],
          depotType: [
            { required: true, message: '请选择仓库类型', trigger: 'change' },
          ],
          depotUseTypeId: [
            { required: true, message: '请选择用途类型', trigger: 'change' },
          ],
          isReceiveConsume: [
            {
              required: false,
              message: '请选择是否以领定消',
              trigger: 'change',
            },
          ],
        },
      }
      let arr = [
        'depotName',
        'depotCode',
        'depotType',
        'depotUseTypeId',
        'isReceiveConsume',
      ]
      formOrgInfo.value.modifyFieldList.forEach((element) => {
        if (arr.indexOf(element.value) !== -1) {
          element['show'] = true
        }
      })
    }
    if (val === false) {
      delete formOrgInfo.value.rules.depotName
      delete formOrgInfo.value.rules.depotCode
      delete formOrgInfo.value.rules.depotType
      delete formOrgInfo.value.rules.depotUseTypeId
      delete formOrgInfo.value.rules.isReceiveConsume
      let arr = [
        'depotName',
        'depotCode',
        'depotType',
        'depotUseTypeId',
        'isReceiveConsume',
      ]
      formOrgInfo.value.modifyFieldList.forEach((element) => {
        if (arr.indexOf(element.value) !== -1) {
          element['show'] = false
        } else {
          element['show'] = true
        }
      })
    }
  },
  { immediate: true }
)

watch(
  () => formOrgInfo.value.modifyData.status,
  (val) => {
    val === 1
      ? (formOrgInfo.value.modifyData.isCreateDepotTemp = true)
      : (formOrgInfo.value.modifyData.isCreateDepotTemp = false)
  },
  {
    deep: true,
  }
)

watch(
  () => treeInfo.value.data,
  () => {
    if (orgRoute.value && orgRoute.value.name === 'organization') {
      return
    }
    UserBox.value = false
    showDeptSubmitBox.value = false
    addBtn.value = true
    saveBtn.value = true
    // formOrgInfo.value.ref.resetFields();
  },
  {
    deep: true,
  }
)

watch(
  () => $route,
  (route) => {
    proxy.$nextTick(() => {
      proxy.$forceUpdate()
    })
    orgRoute.value = route
    const params = route.params
    if (route.name === 'organization') {
      init(params)
    }
  },
  {
    immediate: true,
  }
)
onActivated(() => {
  orgRoute.value = proxy.$route
  const params = proxy.$route.params
  if (proxy.$route.name === 'organization') {
    init(params)
  }
})
onMounted(() => {
  getConfigList()
  initRules()
  if (orgRoute.value && orgRoute.value.name === 'organization') {
    return
  }
  init()
})

function selectDeptClassfication() {
  selectManageClassfication.value.visible = true
}
function selectDeptUser() {
  selectUserInfo.value.visible = true
}
function selectUserInfoBack(data) {
  if (data && data.id) {
    formOrgInfo.value.data['managerUserName'] = data.name
    formOrgInfo.value.data['managerUserId'] = data.id
  } else {
    formOrgInfo.value.data['managerUserName'] = ''
    formOrgInfo.value.data['managerUserId'] = ''
  }
}
function selectManageClassficationBack(data) {
  if (data && data.id) {
    if (modifyInfo.value.visible) {
      formOrgInfo.value.modifyData['deptClassificationValue'] = data.name
      formOrgInfo.value.modifyData['deptClassificationId'] = data.id
    } else {
      formOrgInfo.value.data['deptClassificationValue'] = data.name
      formOrgInfo.value.data['deptClassificationId'] = data.id
    }
  } else {
    formOrgInfo.value.data['deptClassificationValue'] = ''
    formOrgInfo.value.data['deptClassificationId'] = ''
    formOrgInfo.value.modifyData['deptClassificationValue'] = data.name
    formOrgInfo.value.modifyData['deptClassificationId'] = data.id
  }
}
function viewImg(row, index) {
  //查看图片
  if (
    row.electronicSignaturePaths &&
    row.electronicSignaturePaths.length &&
    row.electronicSignaturePaths[0].filePath
  ) {
    viewImgInfo.value.row = row
    viewImgInfo.value.index = index
    viewImgInfo.value.visible = true
    viewImgInfo.value.list = [
      {
        name: row.electronicSignaturePaths[0].filePath,
        url: baseUrl.value + '/pub' + row.electronicSignaturePaths[0].filePath,
        uid: new Date().getTime() + (1 + Math.random()),
      },
    ]
  }
}
function callbackEle() {
  let row = proxy.$fn.deepClone(viewImgInfo.value.row)
  row.electronicSignaturePaths = []
  updateElectronicSignaturePath(row).then((res) => {
    if (res && res.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function upDateUpload(res) {
  let params = proxy.$fn.deepClone(tableInfo.value.data[res.index])
  params.electronicSignaturePaths = [
    {
      filePath: res.data[0],
    },
  ]
  updateUser(params).then((res) => {
    if (res && res.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
// 获取列表
function getConfigList() {
  let arr = [
    {
      label: '新增',
      value: 'add',
      show: proxy.$permission('organization:add'),
    },
    {
      label: '删除',
      value: 'delDept',
      show: proxy.$permission('organization:del'),
    },
    {
      label: '下载部门模板',
      value: 'orgDeptImport',
      show: proxy.$permission('organization:downloadDeptTemplate'),
    },
    {
      label: '导入部门',
      value: 'orgDeptInput',
      show: proxy.$permission('organization:deptImport'),
    },
    {
      label: '下载人员模板',
      value: 'orgUserImport',
      show: proxy.$permission('organization:downloadUserTemplate'),
    },
    {
      label: '导入人员',
      value: 'orgUserInput',
      show: proxy.$permission('organization:userImport'),
    },
    {
      label: '导出Excel',
      value: 'exportExcel',
      show: proxy.$permission('organization:exportExcel'),
    },
  ]
  let list = arr.filter((item) => item.show)
  if (list.length > 0) {
    btnList.value.beforeList = list.slice(0, 2)
    btnList.value.afterList = list.slice(2, list.length)
  }
}
function exportExcel(){
  let params = {}
  if(treeInfo.value.query.keyword){
    params = treeInfo.value.query
  }
  exportDets(params).then(resp => {
    if(resp){
      proxy.$fn.parseExcel(resp)
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function del(row) {
  if (row && row.id) {
    remove([row.id])
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = tableInfo.value.selections.map((row) => row.id)
        remove(ids)
      })
  }
}
function remove(ids) {
  deleteUser(ids).then((resp) => {
    if (resp && resp.success) {
      loadUserList(currentDeptId.value)
    }
  })
}
//人员停用或者启用
function enableOrdis(row) {
  row.status = row.status == 1 ? 0 : 1
  updateUser(row).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    } else {
      loadUserList(currentDeptId.value)
    }
  })
}
//人员停锁定解锁
function unlock(row) {
  row.locked = row.locked == 1 ? 0 : 1
  updateUser(row).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    } else {
      loadUserList(currentDeptId.value)
    }
  })
}
// 加载组织架构
function init(params) {
  console.info(params)
  getDeptTrees(treeInfo.value.query).then((res) => {
    if (res.success) {
      treeInfo.value.data = res.data
      if (treeInfo.value.query.keyword) {
        showDeptSubmitBox.value = false
        UserBox.value = false
      }
      if (params && params.deptId) {
        getTreeItem(res.data, params)
      } else if (params && params.id) {
        getTreeItem(res.data, params)
      }
    }
  })
}
function getTreeItem(data, param) {
  data.forEach((item) => {
    if (item.children && item.children.length) {
      getTreeItem(item.children, param)
    }
    if (item.id.toString() === param.deptId) {
      handleNodeClick(item)
      return
    } else if (item.id === param.id) {
      handleNodeClick(item)
      proxy.$nextTick(function () {
        proxy.$refs.menuTree.setCurrentKey(item.id)
      })
      return
    }
  })
}
// 初始化校验规则
function initRules() {
  //const formOrgInfo = formOrgInfo.value;
  // formOrgInfo.rules = proxy.$initRules(formOrgInfo.fieldList);
}
//添加部门
function addOrg() {
  addOrUpdate.value = createDeptWithPrimaryKey
  addOrUpdateType.value = 'createDeptWithPrimaryKey'
  formOrgInfo.value.modifyData = {}
  let parent = proxy.$refs.menuTree.getCurrentNode()
  formOrgInfo.value.modifyData = {
    pid: parent.id,
    ownAllProduct: '1',
    status: 1,
    deptClassificationValue: '',
    isAllDept: false,
    isAllDepot: false,
    isAllSupplier: false,
    isCreateDepotTemp: true,
  }
  modifyInfo.value.visible = true
}
function closeModifyDept() {
  modifyInfo.value.visible = false
}
//删除部门
function delDept() {
  const ids = [currentDeptId.value]
  proxy.$handleAPI('delete', deleteDept, ids).then((resp) => {
    if (resp && resp.success) {
      formOrgInfo.value.data = {}
      userFormInfo.value.data = {}
      tableInfo.value.data = []
      tableInfo.value.selections = []
      init()
    }
  })
}
// 获取部门信息和部门内人员列表
function getOrgDetail(node) {
  getDeptDetail(node.id).then((res) => {
    formOrgInfo.value.data = {
      ...res.data,
      isAllDept: res.data.isAllDept === 1 ? true : false,
      isAllDepot: res.data.isAllDepot === 1 ? true : false,
      isAllSupplier: res.data.isAllSupplier === 1 ? true : false,
    }
    if (formOrgInfo.value.data.status === 1) {
      canNotAddUser.value = false
    } else {
      canNotAddUser.value = true
    }
  })
}
// 关闭用户弹窗
function closeUserDialog() {
  userDialogInfo.value.visible = false
}
function closeUserInfoDetails() {
  userInfoDetails.value.visible = false
}
function openUserInfoDetails(row) {
  infoList.value.data = row
  userInfoDetails.value.visible = true
}
// 加载当前部门下用户列表
function loadUserList(id) {
  filterInfo.value.query.deptId = id <= 0 ? '' : id
  selectUserInfo.value.query.deptId = id <= 0 ? '' : id
  proxy.$nextTick(function () {
    tableInfo.value.refresh = Math.random()
  })
}
// 点击树节点
function handleNodeClick(node) {
  // formOrgInfo.value.ref.resetFields();
  addBtn.value = false
  addOrUpdate.value = updateDept
  addOrUpdateType.value = 'updateDept'
  treeInfo.value.selectNode = node
  currentDeptId.value = node.id
  if (node.id !== -1) {
    saveBtn.value = false
    // 获取部门信息和部门内人员列表
    getOrgDetail(node)
    UserBox.value = true
    showDeptSubmitBox.value = true
    loadUserList(node.id)
  } else {
    formOrgInfo.value.data = {}
    showDeptSubmitBox.value = false
    saveBtn.value = true
    UserBox.value = true
    loadUserList()
  }
}
// 新增用户或编辑
function addUser() {
  if (canNotAddUser.value) {
    proxy.$alert(`该部门已停用，无法添加人员`, '操作提示', {
      confirmButtonText: '确定',
    })
    return
  }
  const _userFormInfo = userFormInfo.value
  _userFormInfo.rules = proxy.$initRules(_userFormInfo.fieldList)
  _userFormInfo.data = {}
  userDialogInfo.value.type = 'create'
  userDialogInfo.value.visible = true
  _userFormInfo.data.type = 'normal'
  _userFormInfo.data.deptId = formOrgInfo.value.data.id
  _userFormInfo.fieldList[8].show = false
  _userFormInfo.fieldList[9].show = false
  _userFormInfo.fieldList[10].show = false
  _userFormInfo.fieldList[11].show = true
  _userFormInfo.fieldList[0].disabled = false
}
function editUser(data) {
  userFormInfo.value.data = {}
  userFormInfo.value.data = JSON.parse(JSON.stringify(data))
  ;(userFormInfo.value.data.isAllDept = userFormInfo.value.data.isAllDept
    ? true
    : false),
    (userFormInfo.value.data.isAllDepot = userFormInfo.value.data.isAllDepot
      ? true
      : false),
    (userFormInfo.value.data.isAllSupplier = userFormInfo.value.data
      .isAllSupplier
      ? true
      : false)
  userFormInfo.value.rules = proxy.$initRules(userFormInfo.value.fieldList)
  userDialogInfo.value.visible = true
  userDialogInfo.value.type = 'update'
  userFormInfo.value.fieldList[8].show = true
  userFormInfo.value.fieldList[9].show = true
  userFormInfo.value.fieldList[10].show = true
  userFormInfo.value.fieldList[11].show = false
  userFormInfo.value.fieldList[0].disabled = true
}
function saveUser() {
  userFormInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      userFormInfo.value.data.isAllDept = userFormInfo.value.data.isAllDept
        ? 1
        : 0
      userFormInfo.value.data.isAllDepot = userFormInfo.value.data.isAllDepot
        ? 1
        : 0
      userFormInfo.value.data.isAllSupplier = userFormInfo.value.data
        .isAllSupplier
        ? 1
        : 0
      const params = userFormInfo.value.data
      const type = userDialogInfo.value.type
      if (type === 'create') {
        api = createUser
      } else if (type === 'update') {
        api = updateUser
      } else {
        return
      }
      api(params).then((res) => {
        if (res.success) {
          userDialogInfo.value.visible = false
          tableInfo.value.refresh = Math.random()
          userFormInfo.value.data = {}
        }
      })
    }
  })
}
function search() {
  const _tableInfo = tableInfo.value
  _tableInfo.initCurpage = Math.random()
  _tableInfo.refresh = Math.random()
}
function addRoles(row) {
  selectRoleInfo.value.defaultList = row.roleIds
  selectRoleInfo.value.visible = true
  selectRoleInfo.value.userId = row.id
}
function addRoleCallback(rows = []) {
  const data = []
  if (rows.length > 0) {
    rows.forEach((item) => {
      data.push({
        userId: selectRoleInfo.value.userId,
        roleId: item.id,
      })
    })
    mappingUserRole(data).then((resp) => {
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    })
  } else {
    //为空的时候 删除该角色已有资源
    let entity = { userId: selectRoleInfo.value.userId }
    deleteMappingUserRole(entity).then((resp) => {
      if (resp && resp.success) {
        loadUserList(currentDeptId.value)
      }
    })
  }
}
// 用户多选
function listSelect(rows) {
  selectRows.value = []
  for (let item of rows) {
    selectRows.value.push(item.id)
  }
}
// 更新或添加部门
function updateOrg() {
  let _formOrgInfo = formOrgInfo.value
  formOrgInfo.value.ref.validate((valid) => {
    if (valid) {
      let params = {}
      if (addOrUpdateType.value === 'createDeptWithPrimaryKey') {
        _formOrgInfo.modifyData.isAllDept = _formOrgInfo.modifyData.isAllDept
          ? 1
          : 0
        _formOrgInfo.modifyData.isAllDepot = _formOrgInfo.modifyData.isAllDepot
          ? 1
          : 0
        _formOrgInfo.modifyData.isAllSupplier = _formOrgInfo.modifyData
          .isAllSupplier
          ? 1
          : 0
        params = _formOrgInfo.modifyData
      } else {
        _formOrgInfo.data.isAllDept = _formOrgInfo.data.isAllDept ? 1 : 0
        _formOrgInfo.data.isAllDepot = _formOrgInfo.data.isAllDepot ? 1 : 0
        _formOrgInfo.data.isAllSupplier = _formOrgInfo.data.isAllSupplier
          ? 1
          : 0
        params = _formOrgInfo.data
      }
      params.isCreateDepot = params.isCreateDepotTemp ? 1 : 0
      addOrUpdate.value(params).then((res) => {
        if (res.success) {
          let param = {}
          //新增部门时 需要insert成功后的部门id  将id传给部门资源的新增方法中使用
          if (addOrUpdate.value.name == 'createDeptWithPrimaryKey') {
            selectResourceInfo.value.subjectId = res.data
            param.id = res.data
          } else {
            selectResourceInfo.value.subjectId = formOrgInfo.value.data.id
            selectResourceInfo.value.subjectType = 'dept'
            selectResourceInfo.value.fromType = 'dept'
            param.id = formOrgInfo.value.data.id
          }
          if (_formOrgInfo.data.status === 1) {
            canNotAddUser.value = false
          } else {
            canNotAddUser.value = true
          }
          closeModifyDept()
          // updateResource(isCascade.value)
          init(param)
          formOrgInfo.value.data.isAllDept =
            _formOrgInfo.data.isAllDept === 1 ? true : false
          formOrgInfo.value.data.isAllDepot =
            _formOrgInfo.data.isAllDepot === 1 ? true : false
          formOrgInfo.value.data.isAllSupplier =
            _formOrgInfo.data.isAllSupplier === 1 ? true : false

          proxy.$message({
            message: `操作成功`,
            type: 'success',
            duration: 1500,
            showClose: true,
          })
        }
      })
    }
  })
}
function addAuth(row) {
  // selectAuthInfo.value.queryTree.userId = row.id;
  selectAuthInfo.value.query.subjectId = row.id
  selectAuthInfo.value.query.disableRole = row.id
  selectAuthInfo.value.queryTree.disableRole = row.id
  selectAuthInfo.value.queryTree.orgId =
    proxy.$store.state.user.userInfo.user.orgId
  selectAuthInfo.value.visible = true
  selectAuthInfo.value.userId = row.id
}
function addAuthCallback(authList = []) {
  if (authList.length) {
    const data = []
    authList.forEach((authNode) => {
      data.push({
        subjectId: selectAuthInfo.value.userId,
        subjectType: 'user',
        resourceType: authNode.type,
        resourceId: authNode.id,
        level: 'own_and_allot',
      })
    })
    batchUpdatePermissions(data).then((res) => {
      if (res && res.success) {
        dialogInfo.value.visible = false
      }
    })
  } else {
    const data = {
      subjectType: 'user',
      subjectId: selectAuthInfo.value.userId,
    }
    deletePermissionsByEntity(data)
  }
}
function addDeptResource() {
  if (addOrUpdateType.value === 'createDeptWithPrimaryKey') {
    return
  } else {
    selectResourceInfo.value.subjectId = formOrgInfo.value.data.id
  }
  selectResourceInfo.value.subjectType = 'dept'
  selectResourceInfo.value.fromType = 'dept'
  userResourceQuery.value = {}
  userResourceDisabledList.value = []
  addResource()
}
async function addUserResource(row) {
  await getResourceDisabled()
  selectResourceInfo.value.subjectType = 'user'
  selectResourceInfo.value.subjectId = row.id
  selectResourceInfo.value.fromType = 'user'
  userResourceQuery.value = {
    disabledDept: currentDeptId.value,
    disabledDepot: currentDeptId.value,
    disabledSupplier: currentDeptId.value,
  }
  addResource()
}
function getResourceDisabled() {
  const deptId = formOrgInfo.value.data.id
  userResourceQuery.value = {}
  const params = {
    subjectId: deptId,
    subjectType: 'dept',
    //排除维保商
    resourceTypeNotIn: 'maintenance',
  }
  getCoreResourcesAll(params).then((res) => {
    if (res && res.success) {
      userResourceDisabledList.value = res.data
    }
  })
}
function addResource() {
  const params = {
    subjectId: selectResourceInfo.value.subjectId,
    subjectType: selectResourceInfo.value.subjectType,
    //排除维保商
    resourceTypeNotIn: 'maintenance',
  }
  getCoreResourcesAll(params).then((res) => {
    if (res && res.success) {
      const selectRow = {
        dept: [],
        depot: [],
        supplier: [],
      }
      console.log(res.data)
      res.data.forEach((item) => {
        selectRow[item.resourceType].push({
          id: item.resourceId,
          selectable: true,
        })
      })
      selectResourceInfo.value.defaultList =
        addOrUpdateType.value === 'createDeptWithPrimaryKey' ? {} : selectRow
      selectResourceInfo.value.visible = true
    }
  })
}
function addResourceCallback(data, _isCascade) {
  isCascade.value = _isCascade
  resourceCallbackData.value[selectResourceInfo.value.subjectType] = data
  resourceKeys.value = Object.keys(data)
  if (selectResourceInfo.value.subjectType === 'user') {
    updateResource()
  } else {
    updateResource(isCascade.value)
  }
}
function updateResource(_isCascade = undefined) {
  if (resourceKeys.value.length) {
    let resources = []
    resourceKeys.value.forEach((key) => {
      resources = resources.concat(
        resourceCallbackData.value[selectResourceInfo.value.subjectType][
          key
        ].map(function (item) {
          if (_isCascade !== undefined) {
            return {
              subjectType: selectResourceInfo.value.subjectType,
              subjectId: selectResourceInfo.value.subjectId,
              resourceType: key,
              resourceId:
                key === 'supplier' && item.supplierId
                  ? item.supplierId
                  : item.id,
              asDefault: item.asDefault,
              isCascade: _isCascade ? 1 : 0,
            }
          } else {
            return {
              subjectType: selectResourceInfo.value.subjectType,
              subjectId: selectResourceInfo.value.subjectId,
              resourceType: key,
              resourceId:
                key === 'supplier' && item.supplierId
                  ? item.supplierId
                  : item.id,
              asDefault: item.asDefault,
            }
          }
        })
      )
    })
    let disabledList = userResourceDisabledList.value.map((item) => {
      if (_isCascade !== undefined) {
        return {
          subjectType: selectResourceInfo.value.subjectType,
          subjectId: selectResourceInfo.value.subjectId,
          resourceType: item.resourceType,
          resourceId: item.resourceId,
          isCascade: _isCascade ? 1 : 0,
        }
      } else {
        return {
          subjectType: selectResourceInfo.value.subjectType,
          subjectId: selectResourceInfo.value.subjectId,
          resourceType: item.resourceType,
          resourceId: item.resourceId,
        }
      }
    })

    let arr = _.differenceWith(resources, disabledList, _.isEqual)
    let params = {
      subjectType: selectResourceInfo.value.subjectType,
      subjectId: selectResourceInfo.value.subjectId,
      resourceList: arr || [],
    }
    // if (arr.length) {
    resourcesUpdateList(params)
    // } else {
    //   let resource = {}
    //   if (_isCascade !== undefined) {
    //     resource = {
    //       subjectId: selectResourceInfo.value.subjectId,
    //       subjectType: selectResourceInfo.value.subjectType,
    //       isCascade: _isCascade ? 1 : 0,
    //     }
    //   } else {
    //     resource = {
    //       subjectId: selectResourceInfo.value.subjectId,
    //       subjectType: selectResourceInfo.value.subjectType,
    //     }
    //   }

    //   // deleteCoreResourcesByEntity(resource)
    // }
  }
  // else {
  //判断是否新增操作还是修改操作 当勾选的资源为空时 如果是修改操作，则删除该用户的所有资源
  // if (
  //   addOrUpdate.value.name == 'updateDept' &&
  //   selectResourceInfo.value.subjectId
  // ) {
  //   let resource = {}
  //   if (_isCascade !== undefined) {
  //     resource = {
  //       subjectId: selectResourceInfo.value.subjectId,
  //       subjectType: selectResourceInfo.value.subjectType,
  //       isCascade: _isCascade ? 1 : 0,
  //     }
  //   } else {
  //     resource = {
  //       subjectId: selectResourceInfo.value.subjectId,
  //       subjectType: selectResourceInfo.value.subjectType,
  //     }
  //   }
  //   // deleteCoreResourcesByEntity(resource)
  // }
  // }
}
function beforeUpload() {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    init()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function resetUserPassword(data) {
  resetPassword(data.userName)
}
function changeDept(row) {
  deptInfo.value.visible = true
  deptInfo.value.query.idNot = currentDeptId.value
  deptInfo.value.userId = row.id
}
function selectDeptCallback(row = undefined) {
  if (row && row.id) {
    proxy
      .$confirm('此操作将更新数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let params = {
          id: deptInfo.value.userId,
          sourceDeptId: currentDeptId.value,
          targetDeptId: row.id,
        }
        adjustDept(params).then((resp) => {
          if (resp && resp.success) {
            search()
          }
        })
      })
      .catch((e) => {})
  }
}
function downloadTemplate(tag) {
  exportTemplateExcel(tag).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 83px);
}
.left-container {
  min-width: 320px;
  .left-container-header {
    display: flex;
    align-items: center;
    //justify-content: space-around;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 240px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
    :deep(.el-tree-node__children) {
      overflow: initial;
    }
  }
}
.img-wraper {
  width: 100px;
  height: 50px;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.showImage {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  .image {
    max-width: 40px !important;
    max-height: 40px !important;
  }
}
:deep(.full) {
  width: 100% !important;
}
</style>
